package com.lewis.system.web.service;

import com.lewis.system.manager.AsyncManager;
import com.lewis.system.manager.factory.AsyncFactory;
import com.lewis.system.service.ISysConfigService;
import com.lewis.core.constant.Constants;
import com.lewis.core.base.domain.entity.SysUser;
import com.lewis.core.base.domain.model.LoginUser;
import com.lewis.core.utils.RedisUtil;
import com.lewis.core.exception.CustomException;
import com.lewis.core.exception.user.CaptchaException;
import com.lewis.core.exception.user.CaptchaExpireException;
import com.lewis.core.exception.user.UserPasswordNotMatchException;
import com.lewis.core.utils.DateUtil;
import com.lewis.core.utils.MessageUtil;
import com.lewis.core.utils.ServletUtil;
import com.lewis.core.utils.ip.IpUtil;
import com.lewis.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 *
 * @author Lewis
 */
@Component
public class SysLoginService {

	@Autowired
	private TokenService tokenService;

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private ISysConfigService sysConfigService;

	/**
	 * 登录验证
	 *
	 * @param username 用户名
	 * @param password 密码
	 * @param code     验证码
	 * @param uuid     唯一标识
	 * @return 结果
	 */
	public String login(String username, String password, String code, String uuid) {
		boolean captchaOnOff = sysConfigService.selectCaptchaOnOff();
		// 验证码开关
		if (captchaOnOff) {
			validateCaptcha(username, code, uuid);
		}
		// 用户验证
		Authentication authentication = null;
		try {
			authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
		} catch (Exception e) {
			if (e instanceof BadCredentialsException) {
				AsyncManager.me().execute(AsyncFactory.recordLoginInFor(username, Constants.LOGIN_FAIL, MessageUtil.message("user.password.not.match")));
				throw new UserPasswordNotMatchException();
			} else {
				AsyncManager.me().execute(AsyncFactory.recordLoginInFor(username, Constants.LOGIN_FAIL, e.getMessage()));
				throw new CustomException(e.getMessage());
			}
		}
		AsyncManager.me().execute(AsyncFactory.recordLoginInFor(username, Constants.LOGIN_SUCCESS, MessageUtil.message("user.login.success")));
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		recordLoginInfo(loginUser.getUser());
		// 生成token
		return tokenService.createToken(loginUser);
	}

	/**
	 * 校验验证码
	 *
	 * @param username 用户名
	 * @param code     验证码
	 * @param uuid     唯一标识
	 * @return 结果
	 */
	public void validateCaptcha(String username, String code, String uuid) {
		String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
		String captcha = redisUtil.getCacheObject(verifyKey);
		redisUtil.deleteObject(verifyKey);
		if (captcha == null) {
			AsyncManager.me().execute(AsyncFactory.recordLoginInFor(username, Constants.LOGIN_FAIL, MessageUtil.message("user.jcaptcha.expire")));
			throw new CaptchaExpireException();
		}
		if (!code.equalsIgnoreCase(captcha)) {
			AsyncManager.me().execute(AsyncFactory.recordLoginInFor(username, Constants.LOGIN_FAIL, MessageUtil.message("user.jcaptcha.error")));
			throw new CaptchaException();
		}
	}

	/**
	 * 记录登录信息
	 */
	public void recordLoginInfo(SysUser user) {
		user.setLoginIp(IpUtil.getIpAddr(ServletUtil.getRequest()));
		user.setLoginDate(DateUtil.getNowDate());
		sysUserService.updateUserProfile(user);
	}
}
